const express = require('express');
const router = express.Router();
const query = require('../config/db');
const jwt = require("jsonwebtoken");

router.post('/create', async (req, res, next) => {
    // 获取前端传递的参数
    let { mid, cid, createdate } = req.body;
    // 判断该用户是否已经报名该课程 如果报了,就提醒已报; 如果没有报名,开始报名
    let sql2 = `select * from e_order where mid='${mid}' and cid='${cid}'`;
    let result2 = await query(sql2);
    if (result2.length > 0) {
        next("该用户已经报名该课程")
        return;
    }
    // 没有报名
    // 下单
    // oid: 当前的时间戳+6位随机数
    let oid = new Date().getTime() + (Math.random() + '').substr(2, 6);
    let sql = `insert into e_order (oid,mid,cid,createdate,status) values ('${oid}','${mid}','${cid}','${createdate}','1')`;
    let result = await query(sql);
    if (result.affectedRows > 0) {
        res.send({
            success: true,
            msg: '报名成功',
            status: 200
        })
    } else {
        next('联系后端,未知错误')
    }
})

// 修改用户信息
router.post('/update_user', async (req, res, next) => {
    let { mid, realname, sex, birthdate } = req.body;
    // 修改
    let sql = `update e_member set realname='${realname}',sex='${sex}',birthdate='${birthdate}' where mid='${mid}'`;
    let result = await query(sql);

    // 判断
    if (result.affectedRows > 0) {
        // 获取修改后的数据
        let sql = `select * from e_member where mid='${mid}'`;
        let result = await query(sql);
        let obj = result[0];
        // 删除obj中的password
        delete obj.password;
        res.send({
            success: true,
            msg: '更新成功',
            status: 200,
            data: {
                ...obj,
                token: req.headers.token
            }
        })
    } else {
        next('更新失败');
    }
})

//修改用户头像
router.post("/upload_ava", async (req, res, next) => {
    //1.接收到文件
    const form = formidable({
        multiples: true,
        uploadDir: path.join(__dirname, "../temp")
    });
    form.parse(req, async (err, text, files) => {
        if (err) {
            next("上传失败")
            return;
        }
        let file = files.ava;
        //2.处理文件到uploads/avatar 

        //原来的地址
        let oldPath = file.path;
        let newName = new Date().getTime() + (Math.random() + '').substr(2, 6) + path.extname(file.name)
        //新地址
        let newPath = path.join(__dirname, "../uploads/avatar", newName)
        // 剪切
        fs.renameSync(oldPath, newPath)

        //3.文件地址取出来，存到数据库
        //取出mid 
        let { mid } = text;
        let photo_url = '/uploads/avatar/' + newName;
        let sql = `update e_member set head_photo_url='${photo_url}' where mid='${mid}'`;
        let result = await query(sql)

        //判断受影响行数
        if (result.affectedRows > 0) {
            let sql = `select * from e_member where mid='${mid}'`;
            let result2 = await query(sql);
            let obj = result2[0]
            delete obj.password
            res.send({
                success: true,
                msg: "头像更新成功",
                status: 200,
                data: {
                    ...obj,
                    //修改成功后，后端给前端返回了修改的数据的信息，还需要将token也返回，方便前端存储，后期传给后端
                    token: req.headers.token
                }

            })
        } else {
            next("头像更新失败")
        }

    })
})


// 获取报名课程信息  
// 前端传mid  后端去数据库做对比
router.get('/course', async (req, res, next) => {
    // console.log(1);
    let { mid } = req.query;
    // console.log(2);
    let sql = `select * from e_course join e_order on e_course.cid=e_order.cid where e_order.mid='${mid}'`;
    let result = await query(sql)
    res.send({
        success: true,
        msg: '查找成功',
        status: 200,
        date: result
    })
})

// 获取播放视频
router.get('/video', async (req, res, next) => {
    let { id } = req.query;
    let sql = `select * from e_video where id='${id}'`;
    let result = await query(sql);
    res.send({
        success: true,
        msg: "查询成功",
        status: 200,
        data: result[0]
    })
})

module.exports = router;